var service = new EbeimService();
$(function() {
	
	$('.j-checkbox').iCheck({
		checkboxClass : 'icheckbox_square-blue',
		increaseArea : '20%'
	});
	
	var $W = $(window).width();
	var $H = $(window).height();
	var w = $(".window").width(); 
	var h = $(".window").height();
	$(".window").css("top",(($H-h)/2)-80);
	$(".window").css("left",($W-w)/2);
	
	service.getDataSourcesByPage($offset,1000,"2","","",dsCB);
	$(".show-add").click(function(){
		showDialog("addSafeData");
	});
	
	setInterval("getDownloadProcessBar()", 2500);
});

function getDownloadProcessBar() {

	var ids = "";
	$(".bartd").each(function() {
		ids += $(this).attr("nid") + ",";
	});
	if (ids.length > 0) {
		ids = ids.substring(0, ids.length - 1);
		service.getDownloadProcessBar(ids, downloadProcessCB);
		service.deleteDownloadProcessBar(ids, delProcessbarCB);
	}
}

function clicked(thiz,name,dsId,version,dsSecurityRank,status){
	if(dsId!="" && dsId !=undefined){
		$dsId = dsId;
		$version = version;
	}
	if(dsSecurityRank!="" && dsSecurityRank !=undefined){
		$dsSecurityRank = dsSecurityRank;
	}
	$(thiz).parent().find("li").removeClass("z-li-click");
	$(thiz).addClass("z-li-click");
	var r_path = $(thiz).attr("liPath") + "\\" + name;
	$("#h_ab_path").val(r_path);
	var isDir = $(thiz).attr("isDir");
	$("#h_is_directory").val(isDir);
	$("#h_is_ban").val(status);
}

function confirmRecoveryDir(){
	var abDir = $("#ab-recovery-dir").html();
	if(abDir==""){
		$("#tips .dialogContentDiv").html("请选择保险数据的恢复路径！");
		showDialog("tips",2000);
		return;
	}
	$("#h_r_path").val(abDir);
	$("#ab-recovery-dir").html("");
	$(".window").css("display","none");
	recovery();
}

function recovery(){
	var r_path = $("#h_ab_path").val();
	if(r_path == "\\"){
		r_path = "\/";
	}
	var definedPath = $("#h_r_path").val();
	var dynamicCode = $("#dynamicCode").val();
	var nid = $("#h_nid").val();
	if(nid==""){
		nid = $dsId;
	}
	$("#submit").attr("oprt","download");
	service.recoveryFile($dsId, encodeURIComponent(encodeURIComponent("/"+r_path)), $version, dynamicCode, encodeURIComponent(encodeURIComponent(definedPath)) , downloadCB,nid);
}

function selectRecoveryPath(path){
	$("#recoveryWindow").css("display","block");
	var abDir = $("#ab-recovery-dir").html();
	if(abDir!=""){
		$("#ab-recovery-dir").html(abDir+"\\"+path);
		service.getSystemDirs(abDir+"\\"+path, selectRecoveryPathCB);
	}else{
		$("#ab-recovery-dir").html(path);
		service.getSystemDirs(path, selectRecoveryPathCB);
	}
}
function selectRecoveryParentPath(path){
	var abDir = $("#ab-recovery-dir").html();
	var idx = abDir.lastIndexOf("\\");
	if(idx!=-1){
		abDir = abDir.substring(0,idx);
		$("#ab-recovery-dir").html(abDir);
    	service.getSystemDirs(abDir, selectRecoveryPathCB);
	}else{
		$("#ab-recovery-dir").html("");
		service.getSystemDirs("", selectRecoveryPathCB);
	}
}
var selectRecoveryPathCB = function(data){
	var json = eval("("+data+")");
	var content = "";
	for (var i = 0; i < json.length; i++) {
		var name = json[i].name;
		if(i==0){
			 var name = name.split("\\").join("\\\\");
		}
		content = content +
		"<li><a href='javascript:selectRecoveryPath(\""+name+"/\")'>"+name+"</a></li>";
	}
	$(".w-dir-list ul").html(content);
}

function directors(){
	var content = "";
	for (var i = $version; i > ($version>5?$version-5:0); i--) {
		content = content
		+"<li>" 
		+"<span style='float:left;'><button onclick='selectRecoveryPath(\"\")' class='btn btn-success'>恢复至</button></span>"
		+"<span style='float:right;'>版本【"+(i*1)+".0】</span>"
		+"</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
}
function files(){
	var r_path = $("#h_ab_path").val();
	if(r_path == "\\"){
		r_path = "\/";
	}
	var service1 = new EbeimService();
	service1.getFileChangeLog($dsId, encodeURIComponent(encodeURIComponent(r_path)), $version, "", fileChangeLogBC);
}

var fileChangeLogBC = function (data) {
    var jsonStr = eval("(" + data + ")");
    var json = eval("(" + jsonStr + ")");
	var list = json.list.objList;
	
	$("#h_version").val(list[0].version);
	var content = "";
	for (var i = 0; i < (list.length>5?5:list.length); i++) {
		var obj = list[i];
		content = content
		+"<li>"
		+"<span style='float:left;'><button onclick='selectRecoveryPath(\"\")' class='btn btn-success'>恢复至</button></span>"
		+"<span style='float:right;'>"+new Date(obj.logTime).toLocaleString()+"</span>"
		+"</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
};

function download(){
	if($version==undefined || $dsId==undefined){
		$("#tips .dialogContentDiv").html("请先选中一项，在进行下载。");
		showDialog("tips",1000);
		return;
	}
	if($version*1==0){
		$("#tips .dialogContentDiv").html("请先上传该数据。");
		showDialog("tips",1000);
		return;
	}
	var ban = $("#h_is_ban").val();
	if(ban == "4"){
		$("#tips .dialogContentDiv").html("该数据源已被禁用，无法下载!");
		showDialog("tips",1000);
		return;
	}
	var isDir = $("#h_is_directory").val();
	if(isDir == "0"){
		files();
	}else if(isDir == "1"){
		directors();
	}
}

function confirmCode(thiz){
	var oprt = $(thiz).attr("oprt");
	var code = $("#dynamicCode").val();
	if(code == ""){
		$("#tips .dialogContentDiv").html("验证码不能为空!");
		showDialog("tips",1000);
		return;
	}
	if(oprt == "download"){
		recovery();
	}else if(oprt == "upload"){
		upload();
	}else if(oprt == "save"){
		save();
	}else{
		alert("operation is unknown!");
		return;
	}
}

function upload(dsSecurityRank){
	$("#submit").attr("oprt","upload");
	var dynamicCode = $("#dynamicCode").val();
	if($dsId==undefined){
		$("#tips .dialogContentDiv").html("请先选中一项，在进行上传。");
		showDialog("tips",1000);
		return;
	}
	var ban = $("#h_is_ban").val();
	if(ban == "4"){
		$("#tips .dialogContentDiv").html("该数据源已被禁用，无法上传!");
		showDialog("tips",1000);
		return;
	}
	$("#h_dsSecurityRank").val(dsSecurityRank);
	$("#upload").attr("disabled","disabled");
	service.backup($dsId,$dsSecurityRank,dynamicCode,uploadCB);
}

var uploadCB = function(data){
	 $("#upload").removeAttr("disabled");
	 var json = eval("(" + data + ")");
	 if(json.code == "200" || json.code==200){
		 $("#tips .dialogContentDiv").html("成功加入备份队列!");
		 showDialog("tips",1000);
		 clearDateAndWindow();
		 clearInterval(itv);
    	 itv = setInterval("getProcessbar()", 2000);
	 }else{
		 dsSecurityRankCheck(json.code);
	 }
	 
}

function clearDateAndWindow(){
	$("#dynamicCode").val("");
	$("#ab-dir").html("");
	
	hideDialog("addSafeData");
	hideDialog("versionWindow");
	$('#myModal').modal("hide");
	$(".window").css("display","none");
	$(".shadowDiv").css("display","none");
}

var downloadCB = function(data){
	var json = eval("("+data+")");
	if(json.code=="200" || json.code==200){
		clearDateAndWindow();
	 }else{
		 dsSecurityRankCheck(json.code);
	 }
}

var downloadProcessCB = function(data){
	var json = eval("(" + data + ")");
	var list = json.beans;
	for (var i = 0; i < list.length; i++) {
		var bean = list[i];
		$(".bartd").each(function(){
			var nid = $(this).attr("nid");
			if (nid == bean.nid) {
				$(this).find(".processbar-container").css("display","block");
				var count = bean.count;
				var total = bean.total;
				var percent = (count/total)*100;
				
				if(count >= total){
					$(this).find(".processbar-container").find(".processbar").css("width","100%");
					$(this).find(".processbar-container").find(".percent").html("下载完成！");
				}else if(count == -1){
					$(this).find(".processbar-container").find(".percent").html("<font color='red'>下载失败！</font>");
					service.deleteDownloadProcessBarByNid(nid, function(data){;});
				}else{
					$(this).find(".processbar-container").find(".percent").html("下载进度:"+percent.toFixed(2)+"%");
					$(this).find(".processbar-container").find(".processbar").css("width",percent+"%");
				}
			}
		});
	}
}
var itv;

var dsCB = function(data) {
	$dsId = undefined;
	$version = undefined;
    var json = eval("(" + data + ")");
    var list = json.list;
    var terminalId = json.terminalId;
    var createUserId = json.createUserId;
    $total = json.page.totalRecord;
    $totalpage = Math.ceil($total/1000);
    var str = "";
    for (i = 0; i < list.length; i++) {
        var ds = list[i];
        var version = ds.currentVersionMajor + "." +ds.currentVersionMinor;
        if(ds.terminalId == terminalId && ds.createUserId == createUserId ){
        	var root = ds.root;
        	var idx = root.lastIndexOf("/");
        	if(idx != -1){
        		root = root.substring(idx+1,root.length);
        	}
        	
        	str = str
        	+"<li nid='"+ds.id+"' class='bartd' isDir='1' liPath='' onclick='clicked(this,\"\",\""+ds.id+"\",\""+version+"\",\""+ds.dsSecurityRank+"\",\""+ds.status+"\"),setNid(\""+ds.id+"\")' ondblclick='seeData(\""+ds.id+"\",\""+version+"\")'>"
        	+"<i class='fa fa-folder-open-o'></i><br>"
        	+"<span>"+root+"</span>"
        	+"<div class='processbar-container'><div dsid='"+ds.id+"' nid='"+ds.id+"' class='processbar'></div><div class='percent'>0.00%</div></div>"
        	+"</li>";
        }
    }
    if(list.length>0){
    	 $('.z-safedate ul').html(str);
    	 $("#h_is_directory").val("1");
    	 clearInterval(itv);
    	 itv = setInterval("getProcessbar()", 2000);
    }else{
    	str = 
    	"<li style='height:350px;line-height:350px;text-align: center;width:100%;'>"
    	+"您还没有向保险箱添加过数据哦！立即添加"
		+"<button onclick='showDialog(\"addSafeData\")' class='btn btn-success show-add' style='padding: 2px 10px;font-size: 18px'>"
		+"添加&nbsp;<i class='fa fa-plus' style='font-size:14px;'></i></button>"
		+"</li>";
		$('.z-safedate ul').html(str);
    }
    getDownloadProcessBar();
    getProcessbar();
    
}

var itv;
function getProcessbar(ids){
	var ids = "";
	$(".processbar").each(function(){
		ids += $(this).attr("dsid") + ",";
	});
	if(ids.length > 0){
		ids = ids.substring(0,ids.length -1);
		service.getUploadProcessBar(ids,uploadPrcessBarCB);
		service.deleteUploadProcessBar(ids,delProcessbarCB);
	}
}

var uploadPrcessBarCB = function(data){
	var json = eval("("+data+")");
	var list = json.beans;
	for(var i=0;i<list.length;i++){
		var bean = list[i];
		$(".processbar").each(function(){
			var dsid = $(this).attr("dsid");
			if(dsid == bean.dsId){
				$(this).parent().css("display","block");
				if(bean.count >= bean.total){
					$(this).css("width",100+"%");
					$(this).parent().find(".percent").html("100.00%");
					$(this).parent().css("display","none");
					service.getDataSourcesByPage($offset,1000,"2","","",dsCB);
				}else{
					var width = (bean.count*100/bean.total).toFixed(2);
					$(this).css("width",width+"%");
					
					if(width == 0){
						$(this).parent().find(".percent").html("正在加密中...");
					}else{
						$(this).parent().find(".percent").html("上传进度:"+width+"%");
					}
				}
				
			}
		});
	}
}

var delProcessbarCB = function(data){
	var json = eval("(" + data + ")");
}

var $dsId,$version,$dsSecurityRank;
function seeData(dsId,version){
	$dsId = dsId;
	$version = version;
	if($version*1==0){
		$("#tips .dialogContentDiv").html("请先上传该数据。");
		showDialog("tips",1000);
		return;
	}
	service.getFileList(dsId, version, "", filelistCB);
}

function filelist(path){
	var parentPath = "";
	if (path != "/" || path !="") {
	    parentPath = path.substring(0, path.lastIndexOf("\\"));
	}
	if(path.lastIndexOf("\\")!=-1 && parentPath == ""){
		$("#h_path").val("\\");
	}else{
		$("#h_path").val(parentPath);
	}
	
	service.getFileList($dsId, $version, path, filelistCB);
}

function backPre(){
	var path = $("#h_path").val();
	if(path == ""){
		service.getDataSourcesByPage($offset,1000,"2","","",dsCB);
	}else if(path == "\\"){
		$("#h_path").val("");
		seeData($dsId,$version);
	}else{
		filelist(path);
	}
	
}

var filelistCB = function (data) {
    var json = eval("(" + data + ")");

    var str = "";
    for (i = 0; i < json.length; i++) {
        var ds = json[i];
        var path = ds.path.split("\\").join('\\\\');
    	if(ds.type=="文件"){
    		str = str
        	+"<li nid='"+ds.nid+"' class='bartd' isDir='0' liPath='"+ds.path+"' onclick='clicked(this,\""+ds.name+"\"),setNid(\""+ds.nid+"\")'>"
        	+"<i class='fa fa-file-text-o'></i><br>"
        	+"<span>"+ds.name+"</span>"
        	+"<div class='processbar-container'><div nid='"+ds.nid+"' class='processbar'></div><div class='percent'>0.00%</div></div>"
        	+"</li>";
    	}else{
    		str = str
        	+"<li nid='"+ds.nid+"' class='bartd' isDir='1' liPath='"+ds.path+"' onclick='clicked(this,\"\"),setNid(\""+ds.nid+"\")' ondblclick='filelist(\""+path+"\")'>"
        	+"<i class='fa fa-folder-open-o'></i><br>"
        	+"<span>"+ds.name+"</span>"
        	+"<div class='processbar-container'><div nid='"+ds.nid+"' class='processbar'></div><div class='percent'>0.00%</div></div>"
        	+"</li>";
    	}
    }
    $('.z-safedate ul').html(str);
    getDownloadProcessBar();
};

function setNid(nid){
	$("#h_nid").val(nid);
}

function selectParentPath(path){
	var abDir = $("#ab-dir").html();
	var idx = abDir.lastIndexOf("\\");
	if(idx!=-1){
		abDir = abDir.substring(0,idx);
		$("#ab-dir").html(abDir);
    	service.getSystemDirs(abDir, selectSafeDataPathCB);
	}else{
		$("#ab-dir").html("");
		service.getSystemDirs("", selectSafeDataPathCB);
	}
}
var selectParentPathCB = function(data){
	var json = eval("("+data+")");
	var content = "";
	for (var i = 0; i < json.length; i++) {
		content = content +
		"<li><a href='javascript:selectSafeDataPath(\""+json[i].name+"/\")'>"+json[i].name+"</a></li>";
	}
	$(".w-dir-list ul").html(content);
}

function selectSafeDataPath(path){
	$("#safeDataWindow").css("display","block");
	var abDir = $("#ab-dir").html();
	if(abDir!=""){
		$("#ab-dir").html(abDir+"\\"+path);
		service.getSystemDirs(abDir+"\\"+path, selectSafeDataPathCB);
	}else{
		$("#ab-dir").html(path);
		service.getSystemDirs(path, selectSafeDataPathCB);
	}
}
var selectSafeDataPathCB = function(data){
	var json = eval("("+data+")");
	var content = "";
	for (var i = 0; i < json.length; i++) {
		var name = json[i].name;
		if(i==0){
			 var name = name.split("\\").join("\\\\");
		}
		content = content +
		"<li><a href='javascript:selectSafeDataPath(\""+name+"/\")'>"+name+"</a></li>";
	}
	$(".w-dir-list ul").html(content);
}

function confirmDir(){
	var abDir = $("#ab-dir").html();
	if(abDir==""){
		$("#tips .dialogContentDiv").html("请选择保险数据的路径！");
		showDialog("tips",1000);
		return;
	}
	$("#s_path").val(abDir);
	$("#ab-dir").html("");
	$("#safeDataWindow").css("display","none");
}
function cancelRecoveryDir(){
	$("#ab-recovery-dir").html("");
	$(".window").css("display","none");
}
function cancelDir(){
	$("#ab-dir").html("");
	$(".window").css("display","none");
}
function save(){
	var dynamicCode = $("#dynamicCode").val();
	$("#submit").attr("oprt","save");
	saveSafeDate(dynamicCode);
}
var saveSafeDate = function (dynamicCode) {
	var s_path = $('#s_path').val();
	if(s_path == ""){
		$('#s_path').css("border","solid 1px red");
		$('#s_path').focus();
		return;
	}
	
	var dsNeedKey = 0;
	var dsNeedKeyCked = $("#dsNeedKey")[0].checked;
	if(dsNeedKeyCked){
		dsNeedKey = 1;
	}
	var dsNeedCode = 0;
	var dsNeedCodeCked = $("#dsNeedCode")[0].checked;
	if(dsNeedCodeCked){
		dsNeedCode = 1;
	}
	var s_sec_rank = 0;
	if(dsNeedKey==1 && dsNeedCode==0){
		s_sec_rank = 1;
	}else if(dsNeedKey==0 && dsNeedCode==1){
		s_sec_rank = 2;
	}else if(dsNeedKey==1 && dsNeedCode==1){
		s_sec_rank = 3;
	}
	
	var name = s_path;
	var idx = s_path.lastIndexOf("/");
	if(idx == s_path.length-1){
		s_path = s_path.substring(0,idx);
	}
	idx = s_path.lastIndexOf("/");
	if(idx != -1){
		name = s_path.substring(idx+1,s_path.length);
	}
    var ds = {
        name: name,
        dsType: 2,
        dsSecurityRank:s_sec_rank,
        dynamicCode:dynamicCode
    };
    var bs = {
    		type:2,backupTime: 0
    }
    var isEncrypt = 0;
	var isEncryptCked = $("#isEncrypt")[0].checked;
	if(isEncryptCked){
		isEncrypt = 1;
	}
    var config = {
    		isEncrypt:isEncrypt,
    		root: s_path
    }
    var json = {};
    json["datasource"] = ds;
    json["datasourceConfig"] = config;
    json["backStrategy"] = bs;
    $("#save").attr("disabled","disabled");
    service.addDataSource(json, saveCB);
};
var saveCB = function(data){
	$("#save").removeAttr("disabled");
	var json = eval("("+data+")");
	if(json.code == "200"){
		$("#tips .dialogContentDiv").html("添加成功！");
		showDialog("tips",1000);
		clearDateAndWindow();
		service.getDataSourcesByPage($offset,1000,"2","","",dsCB);
	}else{
		dsSecurityRankCheck(json.code,json.message);
	}
}